<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button type="primary" @click="setdialog = true">新建日程</a-button>
      </div>
    </div>
    <el-container class="school-model index-model">
      <el-header class="row eheader">
        <el-form class="col" :inline="true" size="mini">
          <el-form-item label="班级名称">
            <el-input v-model.lazy="clazz" placeholder="班级名称"></el-input>
          </el-form-item>
          <el-form-item label="校区">
            <el-select size="mini" v-model="schooladdressid" placeholder="请选择">
              <el-option label="取消选择" value></el-option>
              <el-option
                v-for="(item, i) in getschooladdress"
                :key="`1teachingschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教室">
            <el-select size="mini" v-model="schoolclassroomid" placeholder="请选择">
              <el-option label="取消选择" value></el-option>
              <el-option
                v-for="(item, i) in schoolclassroom"
                :key="`2teachingschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教师">
            <el-select size="mini" v-model="schooluserid" placeholder="请选择">
              <el-option label="取消选择" value></el-option>
              <el-option
                v-for="item in schoolteacher"
                :key="item.value"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main style="overflow: visible;">
        <!-- <div class="row justify-content-between">
          <div class="col-3 text-center">
            
          </div>
        </div>-->
        <calendars class="calendars" v-bind="{datas, calendarclick,Monthclick}"></calendars>
      </el-main>
    </el-container>
    <el-dialog title="查看" :visible.sync="outerVisible">
      <el-dialog
        append-to-body
        class="school-form"
        title="班级详情"
        width="510px"
        :visible.sync="setaddress"
      >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
          <el-form-item label="上课日期" prop="starttime">
            <el-date-picker
              :picker-options="pickerOptions"
              v-model="ruleForm.starttime"
              type="date"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="上课时段" prop="schoolclasstime">
            <el-select v-model="ruleForm.schoolclasstime" allow-create placeholder="请选择时间段">
              <el-option
                v-for="(item, i) in returnschoolclasstime"
                :key="`2clazzschedule${i}`"
                :label="`${item.starttime}-${item.endtime}`"
                :value="`${item.starttime}-${item.endtime}`"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课时" prop="hour">
            <el-input-number v-model="ruleForm.hour" :min="1" :max="10" label="描述文字"></el-input-number>
          </el-form-item>
          <el-form-item label="教室" prop="schoolclassroomid">
            <el-select v-model="ruleForm.schoolclassroomid" allow-create placeholder="请选择教室">
              <el-option
                v-for="(item, i) in classroom(ruleForm.schoolclazzid)"
                :key="`4clazzschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教师" prop="schooluserid">
            <el-select v-model="ruleForm.schooluserid" allow-create placeholder="请选择教师">
              <el-option
                v-for="(item, i) in user(ruleForm.schoolclazzid)"
                :key="`5clazzschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="助教">
            <el-select v-model="ruleForm.schooluserids" allow-create placeholder="请选择助教">
              <el-option
                v-for="(item, i) in getschooluser.filter(v=> !v.state)"
                :key="`7clazzschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程内容">
            <el-input v-model="ruleForm.info" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="submitForm" type="primary" plain size="mini">确定</el-button>
        </div>
      </el-dialog>
      <table class="table table-bordered">
        <tr>
          <th scope="row">上课时间</th>
          <td>{{watchdata.data.上课时间}}</td>
        </tr>
        <tr>
          <th scope="row">班级</th>
          <td>{{watchdata.title }}</td>
        </tr>
        <tr>
          <th scope="row">教室</th>
          <td>{{watchdata.classban}}</td>
        </tr>
        <tr>
          <th scope="row">教师</th>
          <td>{{watchdata.data.教师 }}</td>
        </tr>
        <tr>
          <th scope="row">助教</th>
          <td>{{watchdata.data.助教}}</td>
        </tr>
        <tr>
          <th scope="row">课程内容</th>
          <td>{{watchdata.data.课程内容}}</td>
        </tr>
        <tr>
          <th scope="row">课时</th>
          <td>{{watchdata.data.课时}}</td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="warning"
          v-if="Math.round(new Date(ruleForm.starttime)) > Date.now()-1000*3600*24"
          @click="setaddress = true"
        >编辑</el-button>
        <el-button
          type="primary"
          v-if="Math.round(new Date(ruleForm.starttime)) > Date.now()-1000*3600*24"
          @click="del(ruleForm.ID)"
        >删除</el-button>
        <el-button type="primary" @click="outerVisible = false">返回</el-button>
      </div>
    </el-dialog>
    <el-dialog
      append-to-body
      class="school-form"
      title="选择班级"
      width="810px"
      :visible.sync="setdialog"
    >
      <el-table :data="getschoolclazz.filter(v=> v.type!=0)" style="width: 100%">
        <el-table-column prop="name" label="名称" ></el-table-column>
        <el-table-column prop="info" label="所在校区">
          <template slot-scope="scope">{{ getschooladdressbyid( scope.row.schooladdressid).name }}</template>
        </el-table-column>
        <el-table-column prop="studentnum" sortable label="课程">
          <template
            slot-scope="scope"
          >{{ scope.row.schoolcourseid?getschoolcoursebyid( scope.row.schoolcourseid).name:'' }}</template>
        </el-table-column>
        <el-table-column prop="type" sortable label="开班日期" width="120px">
          <template slot-scope="scope">{{ totime(scope.row.starttime) }}</template>
        </el-table-column>
        <el-table-column prop="studentnum" sortable label="结课日期" width="120px">
          <template slot-scope="scope">{{ totime(scope.row.endtime) }}</template>
        </el-table-column>
        <el-table-column prop="address" label="排课">
          <template slot-scope="scope">
            <router-link :to=" {name:'课程安排', params: { ID: scope.row.ID }}">排课</router-link>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setdialog = false">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreatschoolclazzschedule,
  asyncdelschoolclazzschedule,
  asynccheckconflictsschoolclazzschedule
} from "../../../../plugins/api.js";
import calendars from "../../../../components/xiaofei/calendars.vue";
import { conflictvalidator, totime, disabledDate } from "../../../utils.js";
import { groupBy } from "underscore";
import * as moment from "moment";
export default {
  name: "teachingschedule",
  data() {
    return {
      pickerOptions: {
        disabledDate
      },
      timek: Math.round(new Date()),
      watchdata: {
        data: {}
      },
      outerVisible: false,
      ruleForm: {
        starttime: "",
        schoolclasstime: "",
        info: "",
        schooluserids: "",
        schooluserid: "",
        schoolclassroomid: ""
      },
      rules: {
        starttime: [{ required: true, message: "请选择时间", trigger: "blur" }],
        schoolclasstime: [
          { required: true, message: "请选择时间段", trigger: "change" }
        ],
        schooluserid: [
          { required: true, message: "请选择教师", trigger: "change" }
        ],
        schoolclassroomid: [
          { required: true, message: "请选择教室", trigger: "change" }
        ],
        checkList: [
          { required: true, validator: this.ischeckList, trigger: "blur" }
        ]
      },
      setaddress: false,
      typede: 1,
      schooluserid: "",
      schooladdressid: "",
      schoolclassroomid: "",
      clazz: "",
      getschoolclazzschedule: [],
      setdialog: false
    };
  },
  watch: {
    timek() {
      this.start();
    },
    typede() {
      this.start();
    }
  },
  computed: {
    ...mapGetters([
      "getschooladdress",
      "getschoolclassroom",
      "getschooluser",
      "getschoolclazz",
      "getschoolclasstime",
      "getschooladdressbyid",
      "getschoolcoursebyid"
    ]),
    datas() {
      const {
        clazz,
        getschoolclazz,
        schooladdressid,
        schooluserid,
        schoolclassroomid,
        getschedule
      } = this;
      let arr;
      arr = getschoolclazz
        .filter(v => {
          return schooladdressid
            ? v.schooladdressid == schooladdressid
            : true && v.name.toLowerCase().includes(clazz.toLowerCase());
        })
        .map(v => v.ID);
      return getschedule.filter(v => {
        let x = arr.includes(v.schoolclazzid);
        let y = true;
        let z = true;
        if (schooluserid) {
          y = v.schooluserid == schooluserid;
        }
        if (schoolclassroomid) {
          z = v.schoolclassroomid == schoolclassroomid;
        }
        return x && y && z;
      });
    },
    getschedule() {
      const { getschoolclazz, usernameids, datagroup } = this;
      return this.getschoolclazzschedule.map(v => {
        const {
          ID,
          schooluserid,
          schoolclassroomid,
          info,
          schoolclazzid,
          schooluserids,
          starttime,
          schoolclasstime,
          hour
        } = v;
        const a = conflictvalidator(
          v,
          datagroup[new Date(starttime).toLocaleDateString()]
        );
        const color = a ? "#F56C6C" : "#409EFF";
        const size = "#FFFFFF";
        const 教师 = usernameids(schooluserid);
        const 助教 = usernameids(schooluserids);
        const 班级 = getschoolclazz.find(vo => vo.ID == schoolclazzid).name;
        const 教室 = this.getschoolclassroom.find(
          vo => vo.ID == schoolclassroomid
        ).name;
        const 上课时间 = `${new Date(
          starttime
        ).toLocaleDateString()}  ${schoolclasstime}`;
        return {
          start: starttime,
          color,
          size,
          title: 班级,
          schooltime: schoolclasstime,
          classban: 教室,
          key: ID,
          data: {
            教师,
            助教,
            课程内容: info ? info : "",
            上课时间,
            课时: hour
          },
          ...v
        };
      });
    },
    schoolteacher() {
      let { schooladdressid } = this;
      return this.getschooluser.filter(v => {
        if (v.isteacher == 1) {
          if (v.classscope == "*") {
            return true;
          } else {
            let x = v.classscope.split(",");
            if (x.includes(schooladdressid.toString())) {
              return true;
            }
          }
        }
      });
    },
    schoolclassroom() {
      return this.getschoolclassroom.filter(v => {
        if (this.schooladdressid) {
          return true;
        } else {
          return v.schooladdressid == this.schooladdressid ? true : false;
        }
      });
    },
    getTime() {
      const { timek, typede } = this;
      let starttime = new Date(timek);
      let endtime = new Date();

      if (typede === 1) {
        // 周
        starttime = moment(timek)
          .day(-1)
          .format();
        endtime = moment(timek)
          .day(6)
          .format();
      } else if (typede === 2) {
        // 日
        starttime = new Date(timek - 1000 * 3600 * 24);
        endtime = new Date(timek + 1000 * 3600 * 24);
      } else {
        starttime = moment(timek)
          .date(-7)
          .format();
        endtime = moment(timek)
          .date(40)
          .format();
      }
      return {
        starttime,
        endtime
      };
    },
    returnschoolclasstime() {
      const { getschoolclasstime, ruleForm } = this;
      const { schooladdressid, starttime } = ruleForm;
      const n = new Date(starttime).getTime();
      return getschoolclasstime.filter(v => {
        if (v.schooladdressid) {
          return v.schooladdressid == schooladdressid;
        }
        if (n < Date.now()) {
          let nw = new Date().getHours() * 60 + new Date().getMinutes();
          let vw =
            Number(v.starttime.split(":")[0]) * 60 +
            Number(v.starttime.split(":")[1]);
          return nw < vw;
        }
        return true;
      });
    },
    datagroup() {
      const { getschoolclazzschedule } = this;
      return groupBy(getschoolclazzschedule, v =>
        new Date(v.starttime).toLocaleDateString()
      );
    }
  },
  mounted() {
    this.start();
  },
  methods: {
    async start() {
      this.getschoolclazzschedule = await asynccheckconflictsschoolclazzschedule(
        this.getTime
      );
    },
    classroom(ID) {
      if (ID) {
        let { schooladdressid } = this.getschoolclazz.find(v => v.ID == ID);
        return this.getschoolclassroom.filter(
          v => v.schooladdressid == schooladdressid
        );
      }
      return [];
    },
    user(ID) {
      if (ID) {
        let { schooladdressid } = this.getschoolclazz.find(v => v.ID == ID);
        return this.getschooluser.filter(v => {
          if (v.state) return;
          if (v.isteacher == 1) {
            if (v.classscope == "*") {
              return true;
            } else {
              let x = v.classscope.split(",");
              if (x.includes(schooladdressid.toString())) {
                return true;
              }
            }
          }
        });
      }
      return [];
    },
    calendarclick(v) {
      const data = this.getschoolclazzschedule.find(vo => vo.ID == v.key);
      this.watchdata = v;
      const u = JSON.parse(JSON.stringify(data));
      this.ruleForm = u;
      this.ruleForm.schooluserids = u.schooluserids;

      this.outerVisible = true;
    },
    async Monthclick(v, c) {
      this.typede = c;
      this.timek = v.unix() * 1000;
    },
    totime,
    del(ID) {
      this.$confirm("此操作将永久删除该次排课, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncdelschoolclazzschedule({ ID });
            await this.start();
            this.outerVisible = false;
            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败:" + err);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async submitForm() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.ruleForm.ID ? "修改" : " 添加";
          try {
            await asynccreatschoolclazzschedule(this.ruleForm);
            await this.start();
            this.$message.success(`${data}成功`);
            this.setaddress = false;
            this.outerVisible = false;
          } catch (err) {
            this.$message.error(`${data}失败:${err}`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    },
    usernameids(id) {
      if (id) {
        const data = this.getschooluser.find(v => v.ID == id);
        return data ? data.name : "";
      }
      return "";
    }
  },
  components: {
    calendars
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
  .eheader {
    padding-top: 15px;
    .col {
      text-align: center;
    }
    label {
      display: inline-block;
      padding-left: 25px;
      padding-right: 25px;
    }
  }
  .text123 {
    margin-right: 10px;
  }
  .calendars {
    margin-top: -35px;
  }
}
</style>